from rest_framework import status, viewsets, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from django.utils import timezone
from datetime import timedelta

from note.views import NotePagination
from .models import HistoryRecord, Note
from .serializers import HistoryRecordSerializer

class HistoryRecordViewSet(viewsets.ModelViewSet):
    serializer_class = HistoryRecordSerializer
    permission_classes = [permissions.AllowAny]
    pagination_class = NotePagination

    def get_queryset(self):
        # 只返回当前用户的历史记录
        return self.request.user.history_records.all()

    def perform_create(self, serializer):
        # 检查用户是否已登录
        if not self.request.user.is_authenticated:
            # 未登录用户直接返回 200，且不处理历史记录
            return Response({"detail": "Success"}, status=status.HTTP_200_OK)

        note_id = self.request.data.get('note_id')
        try:
            note = Note.objects.get(id=note_id)
        except Note.DoesNotExist:
            return Response({"detail": "Note not found"}, status=status.HTTP_404_NOT_FOUND)

        # 获取当前时间
        now = timezone.now()
        # 计算30分钟之前的时间
        thirty_minutes_ago = now - timedelta(minutes=30)

        # 检查同一用户在30分钟内是否访问过该笔记
        recent_record = HistoryRecord.objects.filter(
            user=self.request.user,
            note=note,
            created_at__gte=thirty_minutes_ago
        ).exists()

        if not recent_record:
            # 如果没有在30分钟内访问过，创建新的历史记录
            serializer.save(user=self.request.user, note=note)

        # 不管是否创建记录，都返回200
        return Response({"detail": "Success"}, status=status.HTTP_200_OK)

    # 清空当前用户的历史记录
    @action(detail=False, methods=['delete'])
    def clear(self, request):
        if request.user.is_authenticated:
            request.user.history_records.all().delete()
            return Response({"status": "history cleared"})
        else:
            return Response({"detail": "User not authenticated"}, status=status.HTTP_401_UNAUTHORIZED)
